import React, { useState } from 'react';

function Music() {
    // 获取已有的音乐 URL
    let existingUrlsString = localStorage.getItem('url');
    let existingUrls = existingUrlsString? existingUrlsString.split(',') : [];

    const [selectedAudios, setSelectedAudios] = useState([]);
    const [isAllSelected, setIsAllSelected] = useState(false);

    // 全选或取消全选
    const handleSelectAll = () => {
        if (isAllSelected) {
            setSelectedAudios([]);
        } else {
            setSelectedAudios(existingUrls.filter(url => url.endsWith('.mp3')));
        }
        setIsAllSelected(!isAllSelected);
    };

    // 单选
    const handleSingleSelect = (url) => {
        if (selectedAudios.includes(url)) {
            setSelectedAudios(selectedAudios.filter(item => item!== url));
        } else {
            setSelectedAudios([...selectedAudios, url]);
        }
    };

    // 删除选中的音乐
    const deleteSelectedAudios = () => {
        const updatedUrls = existingUrls.filter(url =>!selectedAudios.includes(url));
        localStorage.setItem('url', updatedUrls.join(','));
        setSelectedAudios([]);
        setIsAllSelected(false);
    };

    return (
        <div>
            <div>
                <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} />全选
                <button onClick={deleteSelectedAudios}>删除选中</button>
            </div>
            {existingUrls.map((url, index) => {
                if (url.endsWith('.mp3')) {
                    return (
                        <div key={index}>
                            <audio controls src={url} />
                            <input
                                type="checkbox"
                                checked={selectedAudios.includes(url) || isAllSelected}
                                onChange={() => handleSingleSelect(url)}
                            />
                        </div>
                    );
                } else {
                    return null;
                }
            })}
        </div>
    );
}

export default Music;